﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Mysoft.AppStartup.Container.Filters;
using Mysoft.Common.Configuration;
using Mysoft.Common.Extensions;
using System.IdentityModel.Tokens.Jwt;

namespace Mysoft.Core.Filters
{
    /// <summary>
    /// api token过滤器
    /// </summary>
    public class ApiAuthorizeFilter : IAuthorizationFilter
    {
        /// <summary>
        /// 刷新token路由地址
        /// </summary>
        private static readonly string replaceTokenPath = "/api/UserAppService/ReplaceToken";
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            // 验证接口是否继承了IAllowAnonymous
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is IAllowAnonymous) && !context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowAnonymousAttribute))
            {
                //IVerifyAuthorize过滤,校验token合法性
                if (context.Filters.Where(item => item is IVerifyAuthorize).FirstOrDefault() is IVerifyAuthorize tokenFilter)
                {
                    tokenFilter.OnAuthorization(context);
                }
                //过期时间
                DateTime expDate = context.HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Exp).Select(x => x.Value).FirstOrDefault().GetTimeSpmpToDate();
                //动态标识刷新token
                if ((expDate - DateTime.Now).TotalMinutes < AppSetting.JWTToken.AccessExpiration / 3 && context.HttpContext.Request.Path != replaceTokenPath)
                {
                    context.HttpContext.Response.Headers.Add("expire", "1");
                }
            }
        }
    }
}
